package com.fruitshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fruitshop.dto.AddressDTO;
import com.fruitshop.entity.Address;
import com.fruitshop.exception.BusinessException;
import com.fruitshop.mapper.AddressMapper;
import com.fruitshop.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 地址服务实现
 */
@Slf4j
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    
    /**
     * 添加收货地址
     *
     * @param userId     用户ID
     * @param addressDTO 地址数据
     * @return 地址ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long add(Long userId, AddressDTO addressDTO) {
        Address address = new Address();
        BeanUtils.copyProperties(addressDTO, address);
        address.setUserId(userId);
        address.setCreateTime(LocalDateTime.now());
        address.setUpdateTime(LocalDateTime.now());
        
        // 如果是默认地址，则将其他地址设为非默认
        if (addressDTO.getIsDefault() != null && addressDTO.getIsDefault() == 1) {
            update(new LambdaUpdateWrapper<Address>()
                    .eq(Address::getUserId, userId)
                    .set(Address::getIsDefault, 0));
        }
        
        save(address);
        return address.getId();
    }
    
    /**
     * 修改收货地址
     *
     * @param userId     用户ID
     * @param addressDTO 地址数据
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean update(Long userId, AddressDTO addressDTO) {
        Address address = getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getId, addressDTO.getId())
                .eq(Address::getUserId, userId));
        
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        BeanUtils.copyProperties(addressDTO, address);
        address.setUpdateTime(LocalDateTime.now());
        
        // 如果是默认地址，则将其他地址设为非默认
        if (addressDTO.getIsDefault() != null && addressDTO.getIsDefault() == 1) {
            update(new LambdaUpdateWrapper<Address>()
                    .eq(Address::getUserId, userId)
                    .ne(Address::getId, address.getId())
                    .set(Address::getIsDefault, 0));
        }
        
        return updateById(address);
    }
    
    /**
     * 删除收货地址
     *
     * @param userId    用户ID
     * @param addressId 地址ID
     * @return 是否成功
     */
    @Override
    public Boolean delete(Long userId, Long addressId) {
        Address address = getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getId, addressId)
                .eq(Address::getUserId, userId));
        
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        return removeById(addressId);
    }
    
    /**
     * 获取收货地址列表
     *
     * @param userId 用户ID
     * @return 地址列表
     */
    @Override
    public List<Address> list(Long userId) {
        return list(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .orderByDesc(Address::getIsDefault)
                .orderByDesc(Address::getUpdateTime));
    }
    
    /**
     * 获取收货地址详情
     *
     * @param userId    用户ID
     * @param addressId 地址ID
     * @return 地址详情
     */
    @Override
    public Address getDetail(Long userId, Long addressId) {
        Address address = getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getId, addressId)
                .eq(Address::getUserId, userId));
        
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        return address;
    }
    
    /**
     * 设置默认收货地址
     *
     * @param userId    用户ID
     * @param addressId 地址ID
     * @return 是否成功
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean setDefault(Long userId, Long addressId) {
        // 检查地址是否存在
        Address address = getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getId, addressId)
                .eq(Address::getUserId, userId));
        
        if (address == null) {
            throw new BusinessException("地址不存在");
        }
        
        // 将所有地址设为非默认
        update(new LambdaUpdateWrapper<Address>()
                .eq(Address::getUserId, userId)
                .set(Address::getIsDefault, 0));
        
        // 将指定地址设为默认
        return update(new LambdaUpdateWrapper<Address>()
                .eq(Address::getId, addressId)
                .set(Address::getIsDefault, 1)
                .set(Address::getUpdateTime, LocalDateTime.now()));
    }
    
    /**
     * 获取默认收货地址
     *
     * @param userId 用户ID
     * @return 默认地址
     */
    @Override
    public Address getDefault(Long userId) {
        return getOne(new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId)
                .eq(Address::getIsDefault, 1));
    }
} 